package com.db.rome.monitoring.csv;

import au.com.bytecode.opencsv.CSVReader;
import com.db.rome.monitoring.DataStorage;
import org.apache.log4j.Logger;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

/**
 * User: gryaale
 * Date: 8/12/14
 */
public abstract class AbstractCsvReader implements CsvReader {

    protected final DataStorage dataStorage;
    private final Logger log = Logger.getLogger(getClass());

    protected AbstractCsvReader(DataStorage dataStorage) {
        this.dataStorage = dataStorage;
    }

    public void readFile(String filename) {
        try {
            CSVReader csvReader = new CSVReader(new FileReader(filename));
            List<String[]> lines = csvReader.readAll();

            removeHeader(lines);
            removeEofMarker(lines);

            for (String[] cols : lines) {
                process(cols);
            }
        } catch (FileNotFoundException e) {
            log.error("File not found :" + filename, e);
        } catch (IOException e) {
            log.error("Can not read file :" + filename, e);
        }
    }

    protected abstract void process(String[] cols);

    private void removeHeader(List<String[]> lines) {
        lines.remove(0);
    }

    private void removeEofMarker(List<String[]> lines) {
        lines.remove(lines.size() - 1);
    }
}
